﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BlogAppExt.Models
{
    /// <summary>
    /// View Model object for sending a blog post to the view
    /// Includes the post, the user, and all associated comments
    /// </summary>
    public class PostDetailVM
    {
        public BlogPost Post { get; set; }
        public User User { get; set; }
        public List<PostPreview> Comments { get; set; }

        public PostDetailVM()
        {
            Comments = new List<PostPreview>();
        }

        /// <summary>
        /// Stores the BlogPost and finds the associated User and CommentPosts.
        /// </summary>
        /// <param name="post">The BlogPost to display to the user</param>
        /// <param name="users">The list of Users (the correct user will be attached to this</param>
        /// <param name="comments">The list of CommentPosts (the correct comments will be attached)</param>
        public void LoadPosts(BlogPost post, List<User> users, List<CommentPost> comments)
        {
            Post = post;

            User = users.Where(x => x.Id == post.UserId).FirstOrDefault();

            List<CommentPost> selectedComments = comments.Where(x => x.ReplyToId == Post.Id).ToList();

            foreach (var comment in selectedComments)
            {
                var user = users.Where(x => x.Id == comment.UserId).FirstOrDefault();

                Comments.Add(new PostPreview(comment.Id, user.Id, user.NameFirst + " " + user.NameLast, user.Image, comment.Title, comment.Text));
            }
        }

    }
}